package com.sgj.gulimall.ware.config;

import com.sgj.common.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.Binding.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @Author: Guoji Shen
 * @Date: 2021/9/17 14:29
 */
@Slf4j
@Configuration
public class MyRabbitConfig {

    /**
     * 消息自动JSON序列化
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    // /**
    //  * 实时监听队列，如果没有该队列则会自动创建
    //  * @param message
    //  */
    // @RabbitListener(queues = "stock.release.stock.queue")
    // public void handle(Message message) {
    //
    // }

    @Bean
    public Exchange stockEventExchange() {
        return new TopicExchange(RabbitConstant.STOCK_EXCHANGE, true, false);
    }

    @Bean
    public Queue stockReleaseStockQueue() {
        return new Queue(RabbitConstant.STOCK_RELEASE_QUEUE, true, false, false);
    }

    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", RabbitConstant.STOCK_EXCHANGE);
        args.put("x-dead-letter-routing-key", RabbitConstant.ROUTING_KEY_RELEASE);
        args.put("x-message-ttl", 120000);
        return new Queue(RabbitConstant.STOCK_DELAY_QUEUE, true, false, false, args);
    }

    @Bean
    public Binding stockReleaseBinding() {
        return new Binding(RabbitConstant.STOCK_RELEASE_QUEUE, DestinationType.QUEUE,
                RabbitConstant.STOCK_EXCHANGE, RabbitConstant.ROUTING_KEY_RELEASE + ".#", null);
    }

    @Bean
    public Binding stockLockedBinding() {
        return new Binding(RabbitConstant.STOCK_DELAY_QUEUE, DestinationType.QUEUE,
                RabbitConstant.STOCK_EXCHANGE, RabbitConstant.ROUTING_KEY_LOCKED, null);
    }
}